package com.ca.ridersclubapplication;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.BooleanEntity;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.LoginRequester;
import com.ca.ridersclubapplication.request.dto.LoginResult;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.ImmersiveActivity;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.KeyBoardUtil;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ea.ui.core.basic.EAButton;
import com.ea.ui.core.basic.EAInput;
import com.ea.ui.core.basic.EALink;
import com.ea.ui.core.util.Type;

import java.util.Objects;

public class LoginActivity extends ImmersiveActivity {

    //  数据
    private int clickIndex;

    //  头像相关
    private ImageView headerImageView;

    //  连接相关
    private EALink emailErrorLink;
    private EALink passwordErrorLink;
    private EALink registerLink;
    private EALink forgetLink;
    private EALink otherLink;

    //  输入框相关
    private EAInput emailInput;
    private EAInput passwordInput;

    //  按钮相关
    private EAButton loginButton;
    private int btnType;



    //  回调视图
    private CallbackView callbackView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //  检查用户是否已经登录
        if (DataHandler.isLogin(this)) {
            finishAfterTransition();
            return;
        }

        //  加载数据
        initData();

        //  初始化视图
        initView();

        //  因存在其他登录方式，当其他登录方式登录成功后，该Activity应当关闭，并跳转至指定Index页面
        //  因此在数据处理器中添加待更新视图控件
        callbackView = new CallbackView() {
            @Override
            public void update() {
                //  获取数据
                Handleable data = DataHandler.getData("Login");
                if (data instanceof BooleanEntity) {
                    boolean isLogin = ((BooleanEntity) data).getValue();
                    if (isLogin) {
                        MainActivity.gotoPage(clickIndex);
                        finishAfterTransition();
                    }
                }
            }
        };
        DataHandler.putView("Login", callbackView);
    }

    /**
     * 加载数据
     */
    private void initData() {
        Intent intent = getIntent();
        clickIndex = intent.getIntExtra("clickIndex", 0);
    }

    /**
     * 初始化视图
     */
    private void initView() {

        //  头像相关
        headerImageView = findViewById(R.id.iv_header);

        //  连接相关
        emailErrorLink = findViewById(R.id.link_error_email);
        passwordErrorLink = findViewById(R.id.link_error_password);
        registerLink = findViewById(R.id.link_register);
        forgetLink = findViewById(R.id.link_forget);
        otherLink = findViewById(R.id.link_other);

        //  输入框相关
        emailInput = findViewById(R.id.ipt_email);
        passwordInput = findViewById(R.id.ipt_password);

        //  按钮相关
        loginButton = findViewById(R.id.btn_login);

        //  设置按钮
        setLoginButton();

        //  设置链接
        setRegisterLink();
        setForgetLink();
        setOtherLink();

        //  设置输入框
        setEmailInput();
        setPasswordInput();
    }


    /**
     * 设置 register链接
     * 实现：
     *      1、点击跳转 注册账号 界面
     */
    private void setRegisterLink() {

        registerLink.setOnClickListener(view -> {

            //  获取 email输入框是存在内容
            String email = Objects.requireNonNull(emailInput.getText()).toString();

            //  开启 RegisterActivity
            ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                    LoginActivity.this,
                    Pair.create(emailInput, "input:email"),
                    Pair.create(emailErrorLink, "link:email"),
                    Pair.create(passwordInput, "input:password"),
                    Pair.create(passwordErrorLink, "link:password"),
                    Pair.create(loginButton, "button:login"),
                    Pair.create(registerLink, "link:register"));

            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            intent.putExtra("email", email);

            startActivity(
                    intent,
                    options.toBundle());
        });
    }


    /**
     * 设置 forget链接
     * 实现：
     *      1、点击跳转 重置密码 界面
     */
    private void setForgetLink() {
        forgetLink.setOnClickListener(view -> {

            //  获取 email输入框是存在内容
            String email = Objects.requireNonNull(emailInput.getText()).toString();

            //  开启 ForgetActivity
            ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                    LoginActivity.this,
                    Pair.create(emailInput, "input:email"),
                    Pair.create(emailErrorLink, "link:email"),
                    Pair.create(passwordInput, "input:password"),
                    Pair.create(passwordErrorLink, "link:password"),
                    Pair.create(loginButton, "button:login"),
                    Pair.create(forgetLink, "link:forget"));

            Intent intent = new Intent(LoginActivity.this, ForgetActivity.class);
            intent.putExtra("email", email);

            startActivity(
                    intent,
                    options.toBundle());
        });
    }


    /**
     * 设置 other链接
     * 实现：
     *      1、点击跳转 其他登录界面
     */
    private void setOtherLink() {
        otherLink.setOnClickListener(view -> {

            //  获取 email输入框是存在内容
            String email = Objects.requireNonNull(emailInput.getText()).toString();

            //  开启 OtherLoginActivity
            ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                    LoginActivity.this,
                    Pair.create(emailInput, "input:email"),
                    Pair.create(emailErrorLink, "link:email"),
                    Pair.create(passwordInput, "input:password"),
                    Pair.create(passwordErrorLink, "link:password"),
                    Pair.create(loginButton, "button:login"),
                    Pair.create(otherLink, "link:other"));

            Intent intent = new Intent(LoginActivity.this, OtherLoginActivity.class);
            intent.putExtra("email", email);

            startActivity(
                    intent,
                    options.toBundle());
        });
    }


    /**
     * 设置 email 输入框
     * 实现：
     *      1、输入邮箱自动请求并显示头像
     *      2、email输入框 和 password输入框 同时通过校验时，开启登录按钮点击
     */
    private void setEmailInput() {

        KeyBoardUtil.showSoftInput(this, emailInput);

        emailInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {

                    //  email输入框 和 password输入框 内容检查，设置按钮是否可用
                    checkEmailAndPassword();

                    if (emailInput.isVerify()) {

                        String email = Objects.requireNonNull(emailInput.getText()).toString();

                        //  查询账号是否存在
                        AccountRequester.getIdByEmail(LoginActivity.this, email, new AfterExecutor<Long>() {
                            @Override
                            public void execute(Result<Long> result) {
                                if (!result.isSuccess()) {
                                    //  如果账号不存在，则提示用户
                                    emailInput.setType(Type.DANGER);
                                    emailErrorLink.setText(result.getMessage());
                                    headerImageView.setAlpha(0f);
                                }
                                else {
                                    //  如果用户存在，则加载头像
                                    emailErrorLink.setText("");
                                    headerImageView.setAlpha(1f);
                                    ImageUtils.loadCircleImage(LoginActivity.this, FileRequester.HEADER_BY_EMAIL_BASE_URL + email, headerImageView);
                                }
                            }
                        });
                    }
                    else {
                        emailErrorLink.setText("请输入正确的邮箱");
                    }
                }
                else {
                    emailErrorLink.setText("");
                }
            }
        });
    }


    /**
     * 设置 password 输入框
     * 实现：
     *      1、输入内容时，显示校验失败提示
     *      2、email输入框 和 password输入框 同时通过校验时，开启登录按钮点击
     */
    private void setPasswordInput() {

        passwordInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {

                    if (!passwordInput.verify()) {
                        passwordErrorLink.setText(R.string.tip_input_password);
                    }
                    else {
                        passwordErrorLink.setText("");
                    }

                    //  email输入框 和 password输入框 内容检查，设置按钮是否可用
                    checkEmailAndPassword();
                }
                else {
                    passwordErrorLink.setText("");
                }
            }
        });
    }


    /**
     * 验证输入框内容
     */
    private void checkEmailAndPassword() {

        boolean flag = emailInput.isVerify() && passwordInput.isVerify()
                && emailErrorLink.getText().toString().isEmpty() && passwordErrorLink.getText().toString().isEmpty();

        if (flag) {
            loginButton.setType(Type.PRIMARY);
            loginButton.setDisable(false);
        }
        else {
            loginButton.setType(btnType);
            loginButton.setDisable(true);
        }
    }


    /**
     * 设置 登录 按钮
     * 实现：
     *      1、点击登录按钮发起登录请求
     */
    private void setLoginButton() {

        //  缓存按钮原 type
        btnType = loginButton.getType();

        loginButton.setOnClickListener(v -> {

            //  将按钮置为不可用，防止多次点击
            loginButton.setDisable(true);

            if (!passwordInput.verify()) {
                passwordErrorLink.setText(R.string.tip_input_password);
            }

            if (emailInput.verify() && passwordInput.verify()) {

                String email = Objects.requireNonNull(emailInput.getText()).toString();
                String password = Objects.requireNonNull(passwordInput.getText()).toString();
                //  发起登录请求
                LoginRequester.loginByPassword(this, null, email, password, new AfterExecutor<LoginResult>() {
                    @Override
                    public void execute(Result<LoginResult> result) {
                        if (result.isSuccess()) {
                            //  登录成功后关闭当前Activity，跳转到指定Index的页面
                            MainActivity.gotoPage(clickIndex);
                            finishAfterTransition();
                        }
                        else {
                            Toast.makeText(LoginActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  移除回调视图
        DataHandler.removeView("Login", callbackView);
    }
}